﻿using System;
using System.Collections.Generic;
using System.Text;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Profile;
using System.Data;
using Gift.DAL;
using Gift.Model;
using Gift.Model.ENUM;
using Gift.Security;

namespace WebSite.admin.product
{
    public partial class card_add : BaseAdmin
    {

        readonly DALCard theCard = new DALCard();
        readonly dalCompany theCompany = new dalCompany();
        readonly DALCardType theCardType = new DALCardType();

        protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
            {
                this.dpkStartTime.Text = DateTime.Now.ToString("yyyy-MM-dd");
                base.ValidateLoginRule(ERule.AddGiftCard);
                this.BindCompanyList();
                this.BindCardTypeList();
            }
        }

        void BindCardTypeList()
        {
            DataSet ds;
            ds = theCardType.GetList(" 1=1" );
            this.ddlCardType.DataTextField = "Name";
            this.ddlCardType.DataValueField = "Id";
            this.ddlCardType.DataSource = ds.Tables[0].DefaultView;
            this.ddlCardType.DataBind();
            this.ddlCardType.Items.Insert(0, new ExtAspNet.ListItem("请选择...", "-1"));
        }

        void BindCompanyList()
        {
            DataSet dsCompany = theCompany.GetList(" LevelId = 1");
            this.ddlCompany.DataTextField = "Name";
            this.ddlCompany.DataValueField = "Id";
            this.ddlCompany.DataSource = dsCompany.Tables[0].DefaultView;
            this.ddlCompany.DataBind();
            this.ddlCompany.Items.Insert(0,new ExtAspNet.ListItem("请选择...","-1"));
        }



        public string turn(string str)
        {
            str = str.Replace("\n", "+");
            return str;
        }


        //string GenerateBeforCode()
        //{
        //    string sBeforCode = "";
        //    Random random = new Random();
        //    sBeforCode = random.Next(1000, 9999).ToString();
        //    if (theCard.IsExistsBefor(sBeforCode))
        //    {
        //       return GenerateBeforCode();
        //    }
        //    else
        //    {
        //        return sBeforCode;
        //    }
        //}





        private  string BuildExportHTML(DataTable dt)
        {
        
            string result = string.Empty;
            int readCnt = dt.Rows.Count;
            int colCount = dt.Columns.Count;

            int pagerecords = 20000;
            string strTitleRow = "";
            for (int j = 0; j < colCount; j++)
            {
                strTitleRow += dt.Columns[j].ColumnName + "\t";
            }
            strTitleRow += "\r\n";

            StringBuilder strRows = new StringBuilder();
            int cnt = 1;
            for (int i = 0; i < readCnt; i++)
            {
                //strRows.Append("");
                for (int j = 0; j < colCount; j++)
                {
                    if (dt.Columns[j].DataType.Name == "DateTime" || dt.Columns[j].DataType.Name == "SmallDateTime")
                    {
                        if (dt.Rows[i][j].ToString() != string.Empty)
                        {
                            strRows.Append(Convert.ToDateTime(dt.Rows[i][j].ToString()).ToString("yyyy年MM月dd日") + "\t");
                        }
                        else
                            strRows.Append("\t");
                    }
                    else
                    {
                        strRows.Append(dt.Rows[i][j].ToString().Trim() + "\t");
                    }
                }
                strRows.Append("\r\n");
                cnt++;
                if (cnt >= pagerecords)
                {
                    result += strRows.ToString();
                    strRows.Remove(0, strRows.Length);
                    cnt = 1;
                }
            }
            result = strTitleRow + result + strRows.ToString();
            return result;
        }


     
        protected void btnCardDatabase_Click(object sender, EventArgs e)
        {
            this.btnCardDatabase.Enabled = false;
            List<DB_Card> lstCard;
            StringBuilder sbSql = new StringBuilder();
            if (ViewState["cardlist"] != null)
            {
                lstCard = (List<DB_Card>)ViewState["cardlist"];
                foreach (DB_Card theCard in lstCard)
                {

                    sbSql.Append("INSERT INTO DB_Card(cardcode,cardpas,cardprice,starttime,endtime,lasttime,states,cardtypeId,companyId,publishWay,addTime,useWay)");
                    sbSql.Append(" VALUES('" + theCard.cardcode + "','" + DESEncrypt.Encrypt(theCard.cardpas) + "'," + theCard.cardprice.ToString());
                    sbSql.Append(" ,'" + theCard.StartTime.ToString() + "'");
                    sbSql.Append(" ,'" + theCard.endtime.ToString() + "','" + theCard.lasttime.ToString() + "',0," + theCard.cardtypeId.ToString() + "," + theCard.companyId.ToString() + ",'" + this.ddlPublichWay.SelectedItem.Value + "',getdate()");
                    sbSql.Append("," + this.rbtlUseWay.SelectedItem.Value +");");

                }
                SQLAccess.DoSql(sbSql.ToString());
            }
            this.btnCardDatabase.Enabled = false;
            ExtAspNet.Alert.Show("礼品卡添加成功！");
    
        }

        protected void btnGenerateCard_Click(object sender, EventArgs e)
        {
            if (theCard.IsExistsBefor(this.txtBeforNumber.Text.Trim(), this.txtBeforNumber.Text.Trim().Length))
            {
                ExtAspNet.Alert.Show("福点卡数字已存在，请重新输入！");
                return;
            }

            Random random = new Random();
            //  string sBeforCode =  this.befornumber.Value;// GenerateBeforCode();
            List<DB_Card> lstInfo;
            lstInfo = new List<DB_Card>();
            DB_Card theCardInfo;
            DateTime dtStartTime;
            DateTime dtEndTime;
            DateTime dtLastTime;

            if (string.IsNullOrEmpty(this.dpkStartTime.Text.Trim()))
            {
                dtStartTime = DateTime.Now;
            }
            else
            {
                if (DateTime.TryParse(this.dpkStartTime.Text.Trim(), out dtStartTime))
                {
                    dtStartTime = DateTime.Parse(this.dpkStartTime.Text.Trim());
                }
                else
                {
                    dtStartTime = DateTime.Now;
                }
            }

            if (string.IsNullOrEmpty(this.dpkEndTime.Text.Trim()))
            {
                dtEndTime = DateTime.Now.AddMonths(6);
                dtLastTime = DateTime.Now.AddMonths(6);
            }
            else
            {
                if (DateTime.TryParse(this.dpkEndTime.Text.Trim(), out dtEndTime))
                {
                    dtEndTime = DateTime.Parse(this.dpkEndTime.Text.Trim());
                    dtLastTime = DateTime.Parse(this.dpkEndTime.Text.Trim());
                }
                else
                {
                    dtEndTime = DateTime.Now.AddMonths(6);
                    dtLastTime = DateTime.Now.AddMonths(6);
                }
            }


            int money;

            money = int.Parse(this.nbxCardPoits.Text);

            Int64 iBeforeNumber = Int64.Parse(this.txtBeforNumber.Text);
            Int64 iMax = iBeforeNumber + Int64.Parse(this.txtCount.Text);

            int cardPassFrom = 1;
            int cardPassTo = 9;
            int iCardPassCount = int.Parse(this.txtCardPassCount.Text);

            for (int i = 1; i < iCardPassCount; i++)
            {
                cardPassFrom = 10 * cardPassFrom ;
                cardPassTo = 10 * cardPassTo + 9;
            }

            for (Int64 i = iBeforeNumber; i < iMax; i++)
            {
                theCardInfo = new DB_Card();
                theCardInfo.cardcode = i.ToString();
                theCardInfo.cardpas = random.Next(cardPassFrom, cardPassTo).ToString();
                theCardInfo.cardprice = money;
                theCardInfo.StartTime = dtStartTime;
                theCardInfo.endtime = dtEndTime;
                theCardInfo.lasttime = dtLastTime;
                theCardInfo.SPublishWay = this.ddlPublichWay.SelectedItem.Value;
                theCardInfo.cardtypeId = int.Parse(this.ddlCardType.SelectedItem.Value);
                theCardInfo.companyId = this.ddlCompany.SelectedItem.Value == "" ? 0 : int.Parse(this.ddlCompany.SelectedItem.Value);
                theCardInfo.CardTypeName = this.ddlCardType.SelectedItem.Text;
                lstInfo.Add(theCardInfo);
            }
            ViewState["cardlist"] = lstInfo;
            this.Grid1.DataSource = lstInfo;
            this.Grid1.DataBind();
            this.btnCardDatabase.Hidden = false;
            this.btnExportCard.Hidden = false;
        }

        protected void btnExportCard_Click1(object sender, EventArgs e)
        {
            if (ViewState["cardlist"] == null) return;
            List<DB_Card> lstCard = (List<DB_Card>)ViewState["cardlist"];
            DataTable dt = new DataTable();
            dt.Columns.Add(new DataColumn("卡号", Type.GetType("System.String")));
            dt.Columns.Add(new DataColumn("密码", Type.GetType("System.String")));
            dt.Columns.Add(new DataColumn("金额", Type.GetType("System.String")));
            dt.Columns.Add(new DataColumn("礼品卡类别", Type.GetType("System.String")));
            dt.Columns.Add(new DataColumn("开始日期", Type.GetType("System.String")));
            dt.Columns.Add(new DataColumn("截止日期", Type.GetType("System.String")));
            dt.Columns.Add(new DataColumn("发行方式", Type.GetType("System.String")));
            dt.Columns.Add(new DataColumn("使用方式", Type.GetType("System.String")));

            for (int i = 0; i < lstCard.Count; i++)
            {
                DataRow dr = dt.NewRow();
                dr[0] = lstCard[i].cardcode;
                dr[1] = lstCard[i].cardpas;
                dr[2] = int.Parse(lstCard[i].cardprice.ToString()).ToString();
                dr[3] = lstCard[i].CardTypeName;
                dr[4] = lstCard[i].StartTime.ToShortDateString();
                dr[5] = lstCard[i].endtime.ToShortDateString();
                dr[6] = lstCard[i].SPublishWay;
                dr[7] = lstCard[i].UseWay;
                dt.Rows.Add(dr);
            }
            Session["exportFile"] = dt;
            ExtAspNet.Alert.Show("导出卡券", "", "window.open('/admin/product/exportGenerateCard.aspx','_blank');");


     
        }

    }

   
}